const {
	Controller
} = require('dx-router-admin');
const {
	OpendbCityChina
} = require('dx-func-entity');
const _ = require('underscore')
module.exports = class Index extends Controller {
	constructor(ctx) {
		super(ctx);
	}
	async uploadBase64(data){
		return await this.currentService.uploadBase64(data.base64);
	}
	async similar(data){
		return this.$dx.service.talent.findSimilar(data);
	}
	async getTalent(data){
		return this.$dx.service.talent.getTalentsByName(data);
	}
	async getProject(data){
		const result = await this.$dx.service.project.getByTalentId(data);
		return result.map(project=>{
			return {
				_id:project._id,
				name:project.name,
				company_name:project.company_name
			}
		})
	}
	async getBatchTalent(data){
		return this.$dx.service.talent.getBatchTalentsByName(data);
	}
	async searchTalent(data){
		return this.$dx.service.talent.searchTalent(data);
	}
	async user(data){
		if(data._id){
			return this.$dx.getUserInfo(data._id);
		}
		return  this.$dx.error('查询失败')
	}
	async companys(data){
		const where = {};
		if(data.key&&data.value&&data.op){
			where[data.key] = [data.op,data.value];
		}else if(data.name&&_.isObject(data.name)){
			where.name = [data.name.op,data.name.value];
		}
		const result =  await this.$dx.service.company.where(where).limit(500).select();
		return  this.$dx.success("操作成功",result) 
	}
	async talents(data){
		const where = {};
		let from = data.from||'system';
		if(data.key&&data.value&&data.op){
			where[data.key] = [data.op,data.value];
			from = 'outside';
		}else if(data.name&&_.isObject(data.name)){
			where.name = [data.name.op,data.name.value];
		}
		const result =  await this.$dx.service.talent.with(['company']).where(where).limit(100).select();
		return  this.$dx.success("操作成功",result) 
	}
	async projects(param){
		//param.status = ['in',[0,1]];
		const uid = param.uid||'';
		const where = {
			status:1
		};
		if(param.name){
			where.name=['like',param.name.trim()];
		}
		let list = await this.$dx.service.project.where(where).with(['company']).order('create_date','desc').limit(200).select();
		let role;
		if(uid){
			const user = await this.$dx.getUserInfo(uid);
			role = user.role;
		}
		if(!role||!role.includes('admin')){
			list = list.filter(item=>{
				const flag =  item.user_id==uid||(item.cooperate&&item.cooperate.includes(uid));
				return flag;
			})
		}
		return list;
	}
	joinProject(param){
		return this.$dx.service.candidate.joinProject(param);
	}
	async talents2(data={}){
		const where = {};
		if(data.name&&_.isObject(data.name)){
			where.name = ['like%'||data.name.op,data.name.value];
		}
		if(data.company_id&&_.isObject(data.company_id)){
			where.company_id = [data.company_id.op,data.company_id.value];
		}
		if(_.isEmpty(where)){
			return  this.$dx.fail("查询失败",[]); 
		}
		if(data.company_name){
			const clist = await this.$dx.service.company.where({name:['like',data.company_name]}).limit(1000).field('name').select();
			where.company_id = ['in',_.pluck(clist,'_id')];
		}
		const result =  await this.$dx.service.talent.where(where).with(['company']).limit(100).select();
		return  this.$dx.success("操作成功",result) 
	}
	async resume(data){
		const {resume,uid,from,extra} = data;
		this.uid = uid||'';
		this.from = from||'';
		let similar;
		if(resume._id){
			similar = await this.$dx.service.talent.findById(resume._id);
		}
		let workCompanys = [];
		if(similar){
			const _ids = _.pluck(similar.company_list||[],'_id');
			_ids.push(similar.company_id);
			workCompanys = await this.$dx.service.company.findByIds(_.uniq(_ids));
		}
		if(_.isArray(resume.companyList)){
			for(let i=0;i<resume.companyList.length;i++){
				const companyInfo = resume.companyList[i];
				const companyName = companyInfo.name;
				let company;
				if(similar){
					const match = this.$dx.service.talent.checkInList(workCompanys,'name',companyName);//this.$dx.service.talent.checkInclude(companyName,similar.company_name);
					if(match){
						companyInfo.name = match.name;
						companyInfo._id = match._id;
						company = companyInfo;
						continue;
					}
				}
				if(!company){
					company = await this.$dx.service.company.findByName(companyName);
				}
				if (!company) {
					const cdata = {name:companyName,user_id:this.uid,from};
					companyInfo.place&&(cdata.headquarters = companyInfo.place.split('-')[0]);
					companyInfo.service&&(cdata.service = companyInfo.service.join('、'));
					companyInfo.scale&&(cdata.scale = companyInfo.scale);
					const _id = await this.$dx.service.company.insert(cdata);
					company = {
						_id:_id
					}
				}
				companyInfo._id = company._id;
			}
		}else{
			resume.companyList = [];
		}
		
		// return {
		// 	similar:similar.company_list,
		// 	resume:resume.companyList
		// };
		/* 合并 历史工作公司 START*/
		
		if(similar){
			//resume.job = similar.job;
			resume.company = similar.company_name; //注意：这样才不会断开系统公司的关联关系
			if(similar.link){
				if(!similar.link2){
					resume.link2 = resume.link;
				}else if(from!='maimai'){
					resume.link2 = resume.link;
				}
				resume.link = similar.link;
				if(resume.link2&&resume.link2.includes(resume.link.substr(0,20))){
					delete resume.link2;
				}
			}
			if(similar.from =='liepin'&&from!='liepin'){
				resume.from = similar.from;
				delete resume.extra;
			}
			if(similar.from =='zhaopin'&&from!='liepin'){
				resume.from = similar.from;
				delete resume.extra;
			}
			//resume.name = similar.name;
			(similar.company_list||[]).forEach(item=>{
				const company = _.findWhere(resume.companyList,{_id:item._id});
				if(!company){
					resume.companyList.push(item);
				}else{
					const work = company.work;
					Object.assign(company,{...item},{...company});
				}
				
			})
			if(similar.company_id){
				const company = _.findWhere(resume.companyList,{_id:similar.company_id});
				if(!company){
					resume.companyList.push({
						name:similar.company_name,
						job:similar.job,
						_id:similar.company_id
					});
				}
			}
		}
		/* 合并 历史工作公司 END*/
		// const similar = await this.$dx.service.talent.findSimilar(resume);
		const response = await this.$dx.service.talent.insertTalent(data);
		return {
			...response
		};
		// return {
		// 	code:200,
		// 	data:data,
		// 	message:'获取上传简历信息'
		// }
	}
	async upload({list,uid,from}){
		this.uid = uid||'';
		this.from = from||'';
		if(!uid){
			return {
					code:500,
					message:'未识别到用户信息请登录后重试'
			}
		}else{
			const userInfo = await this.$dx.getUserInfo(uid);
			if(!userInfo||userInfo.status!=0){
				return {
						code:500,
						message:'当前用户已禁用,请联系管理员'
				}
			}
		}
		
		const count = await this.batchUpload(list,0);
		if(_.isNumber(count)){
			if(count==0){
				return {
					code:200,
					count,
					message:'数据已存在，无需重复导入'
				}
			}
			return {
				code:200,
				count,
				message:`成功导入${count}条职位数据`
			}
		}
		return count;
	}
	async batchUpload(list = [],sucCount=0) {
		if(_.isEmpty(list)){
			return sucCount;
		}
		//return this.$dx.success('保存成功');
		try {
			const companyName = list[0].companyName;
			let company = await this.$dx.service.company.findByName(companyName);
			if (!company) {
				const result = await this.$dx.service.company.save({
					name: list[0].companyName,
					user_id:this.uid,
					parter:true,
					service: list[0].companyTags.join('、'),
					scale: list[0].companyScale
				});
				if (result) {
					company = await this.$dx.service.company.where('name', companyName).find();
				} else {
					throw new Error('创建客户失败～');
				}
			}
			const partList = _.partition(list,job=>{
				return job.companyName==companyName;
			});
			/***************** 合并去重HR START************************/
			const hrlist = await this.$dx.service.talent.findByIds(company.hrlist);
			// 当前公司的所有职位
			for(let i=0;i<partList[0].length;i++){
				const job = partList[0][i];
				/************ 更新  hr 简历************************/
				const jobs = await this.$dx.service.job.getJobs({
					company_id:company._id,
					name:job.name,
					//hr:job.hr,
					//hr_id:hr._id
				});
				if(!_.isEmpty(jobs)){
					await this.$dx.service.job.where('_id','in',_.pluck(jobs,'_id')).update({
						editor_id:this.uid,
						update_date:new Date().getTime()
					});
					//console.error(job.companyName,'：存在同名职位  ',job.name); 
					continue;
				}
				
				/************更新 HR ********************************/
				const hr = _.findWhere(hrlist,{name:job.hr});
				
				//return;
				if(!hr){
					const hr_id = await this.$dx.service.talent.insert({
						name:job.hr,
						from:this.from,
						job: job.hrjob,
						user_id:this.uid,
						company_id:company._id
					});
					job.hr_id = hr_id;
					hrlist.push({
						_id:hr_id,
						name:job.hr
					})
				}else{
					job.hr_id = hr._id;
				}
				/* 保存职位信息*/
				const result = await this.$dx.service.job.save({
					name:job.name,
					location:job.location,
					salary:job.salary,
					salary_year:job.salary_year,
					company_id:company._id,
					//hr:job.hr,
					//hrjob:job.hrjob,
					from:this.from,
					user_id:this.uid,
					hr_id:job.hr_id,
					link:job.link,			
				});
				if(result)sucCount++;
			}
			// 更新公司 HR 列表
			if(hrlist.length>company.hrlist.length){
				
				let result = await this.$dx.service.company.update({ //更新 HR 信息
					_id:company._id,
					parter:true,
					hrlist:_.pluck(hrlist,'_id')
				});
			}
			/***************** 合并去重HR END************************/
			if(partList[1].length==0){
				return sucCount;
			}
			return this.batchUpload(partList[1],sucCount)
		} catch (e) {
			console.error(e);
			return {
				code:500,
				count:sucCount,
				message:'操作失败'
			}
			//this.$dx.error('操作失败')
		}
		//console.log(company, 333)
		// list.forEach(job=>{
		// 	const { companyName } = job;
		// 	console.info(companyName)
		// });
		// let company = await this.$dx.service.company.where('name','123').find();


		//console.error('service111:',company,list);

	}
	async patentJob(param){
		
		if(!param._id){
			return this.$dx.error('暂无公司信息，请稍后重试');
		}
		if(_.isEmpty(param.list)){
			await this.$dx.service.talent.where({company_id:param._id,name:['in',param.names]}).update({
				searched:1
			});
			return this.$dx.error('暂无结果信息，请稍后重试');
		}
		const userObj = {};
		param.list.forEach(info=>{
			if(userObj[info.name]){
				userObj[info.name].push(info);
			}else{
				userObj[info.name] = [info]; 
			}
		})
		const names = Object.keys(userObj);
		for(let i=0;i<names.length;i++){
			const name = names[i];
			const nlist = [];
			const list = userObj[name].map(item=>{
				const info =  {
					from:item.from,
					href:item.href,
					level:item.level,
					word:item.word
				}
				const isExist = _.findWhere(nlist,{level:item.level});
				if(!isExist){
					nlist.push(info)
				}
				return info;
			});
			await this.$dx.service.talent.where({company_id:param._id,name}).update({
				searched:1,
				searchresult:nlist
			});
		}
		/*******************批量更新搜索状态 searched为 1(已搜索)**********************/
		await this.$dx.service.talent.where({company_id:param._id,name:['in',param.names]}).update({
			searched:1
		});
		return this.$dx.success('更新成功');;
	}
};